#include<iostream>
using namespace std;


struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};
 
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode* minRoot = new ListNode(-1, nullptr);
        ListNode* maxRoot = new ListNode(-1, nullptr);
        ListNode* root = new ListNode(-1, head);

        ListNode* pminCur = minRoot;
        ListNode* pmaxCur = maxRoot;
        while (root->next != nullptr) {
            if (root->next->val < x) {
                pminCur->next = root->next;
                root->next = root->next->next;
                pminCur = pminCur->next;
                pminCur->next = nullptr;
            }
            else {
                pmaxCur->next = root->next;
                root->next = root->next->next;
                pmaxCur = pmaxCur->next;
                pmaxCur->next = nullptr;
            }
        }
        pminCur->next = maxRoot->next;
        head = minRoot->next;
        return head;
    }
};

